package com.buba.livenuniappservernew.api.login.controller;


import com.buba.livenuniappservernew.api.MemberUserManagement.entity.MemberUserManagement;
import com.buba.livenuniappservernew.api.MemberUserManagement.service.IMemberUserManagementLoginService;

import com.buba.livenuniappservernew.api.login.service.LoginService;
import com.buba.livenuniappservernew.common.CommonResult;
import com.buba.livenuniappservernew.utils.RandomUtil;
import com.buba.livenuniappservernew.utils.RedisUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员用户表 前端控制器
 * </p>
 *
 * @author 马鼎
 * @since 2024-09-10
 */
@RestController
@RequestMapping("/MemberUserManagementController")
@CrossOrigin
public class MemberUserManagemenLoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 发送手机验证码
     * @param phone
     */
    @ApiOperation("发送手机验证码")
    @GetMapping("/sendInterAspect")
    public void sendMsm(@Param("phone") String phone){
        // 从redis获取验证码，如果获取到直接返回
        Object code = redisUtil.get(phone);
        if(code != null) {
            return;
        }
        // 如果redis获取不到，进行阿里云发送
        //生成随机数
        code = RandomUtil.getFourBitRandom();
        Map map = new HashMap();
        map.put("code",code);
        Boolean b = loginService.send(map,phone);
        if (b){
            //如果发送成功，就把验证码存到redis里，设置2分钟有效时间
            redisUtil.set(phone,code,12000);
            System.out.println("succeed");
            System.out.println("验证码为"+code);
        }else {
            System.out.println("fail");
        }
    }
    @ApiOperation("发送手机验证码")
    @PostMapping("/userPhoneLogin")
    public CommonResult userPhoneLogin(@RequestBody MemberUserManagement memberUserManagement){
        String phoneCode = redisUtil.get(memberUserManagement.getMemberUserPhone()).toString();
        if (phoneCode.isEmpty()){
            return CommonResult.error(500,"请发送验证码");
        }
        if (phoneCode.equals(memberUserManagement.getPhoneCode())){
            return loginService.userPhoneLogin(memberUserManagement);
        }else {
            return CommonResult.error(500,"请输入正确验证码");
        }

    }


}
